package com.zoweunion.mechanic.service.app.impl;

import cn.jpush.api.push.PushResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zoweunion.mechanic.dao.app.AppDao;
import com.zoweunion.mechanic.dao.app.OrderDao;
import com.zoweunion.mechanic.dao.app.PersonalCenterMapper;
import com.zoweunion.mechanic.dao.base.MessageRecordDao;
import com.zoweunion.mechanic.dao.base.UserDao;
import com.zoweunion.mechanic.model.User;
import com.zoweunion.mechanic.model.app.IntegrationExchangeRecord;
import com.zoweunion.mechanic.model.app.IntegrationGoods;
import com.zoweunion.mechanic.model.app.IntegrationRecord;
import com.zoweunion.mechanic.model.app.TaskConfig;
import com.zoweunion.mechanic.plugins.jpush.JiguangPush;
import com.zoweunion.mechanic.service.app.PersonalCenterService;
import com.zoweunion.mechanic.service.base.BaseService;
import com.zoweunion.mechanic.util.JiGuangPushUtil;
import com.zoweunion.mechanic.util.MyException;
import com.zoweunion.mechanic.util.Page;
import com.zoweunion.mechanic.util.UuidUtil;
import com.zoweunion.mechanic.util.constants.Constants;
import com.zoweunion.mechanic.util.constants.PushConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import static com.zoweunion.mechanic.util.FunUtil.logger;

@Service
public class PersonalCenterServiceImpl extends BaseService implements PersonalCenterService {
    @Autowired
    private PersonalCenterMapper personalCenterMapper;
    @Autowired
    private UserDao userDao;
    @Autowired
    private MessageRecordDao messageRecordDao;
    @Autowired
    private JiguangPush jiguangPush;
    @Autowired
    private OrderDao orderDao;

    @Autowired
    private JiGuangPushUtil jiGuangPushUtil;

    @Autowired
    private AppDao appDao;

    /**
     * 获取我的任务列表
     * @param currentUser
     * @param reqMap
     * @return
     */
    @Override
    public List<Map<String, Object>> myTaskList(User currentUser, Map<String, Object> reqMap) {
        reqMap.put("userId", currentUser.getId());
        List<Map<String, Object>> taskRecordList = personalCenterMapper.listUserTask(reqMap);
        for (Map<String, Object> taskRecord : taskRecordList) {
            // 如果是一次性任务，判断是否已经完成
            if ("3".equals(taskRecord.get("type"))) {
                if (this.isCompletedOnceTask(currentUser.getId(), taskRecord.get("id").toString(), Integer.valueOf(taskRecord.get("times").toString()))) {
                    taskRecord.put("isCompleted", 1);
                    taskRecord.put("completedTimes", 1);
                }
            }
        }
        return taskRecordList;
    }

    private boolean isCompletedOnceTask(String userId, String taskId, int needTimes){
        int completedTimes = personalCenterMapper.getCompletedTimesByUserId(userId, taskId, false);
        return completedTimes >= needTimes;
    }

    /**
     * 获取我的完成列表
     * @param currentUser
     * @param reqMap
     * @return
     */
    @Override
    public List<Map> myCompletedTaskList(User currentUser, Map<String, Object> reqMap) {
        reqMap.put("userId", currentUser.getId());
        //今天完成的任务
        List<Map> list = personalCenterMapper.listUserCompletedTask(reqMap);
        //若超过每日最大次数后 今天的完成次数不变 为最大值
        for(Map map:list){
            //获取每日完成的最大次数
           String taskId = map.get("taskId").toString();
           int completeTimes = personalCenterMapper.getTaskTimes(taskId);
           map.put("completedTimes",completeTimes);
        }
        //去掉当天的一次性任务
        Iterator<Map> listIterator = list.iterator();
        while(listIterator.hasNext()){
            Map map = listIterator.next();
            if("3".equals(map.get("type"))){
                listIterator.remove();
            }
        }
        //加上当天的一次性任务
        List<Map> oneTimeTaskList = personalCenterMapper.getOneTimeTask(reqMap);
        for(Map taskRecord:oneTimeTaskList){
            if ("3".equals(taskRecord.get("type"))) {
                if (this.isCompletedOnceTask(currentUser.getId(), taskRecord.get("id").toString(), Integer.valueOf(taskRecord.get("times").toString()))) {
                    taskRecord.put("isCompleted", 1);
                    taskRecord.put("completedTimes", 1);
                    list.add(taskRecord);
                }
            }
        }
        return list;
    }

    /**
     * 完成任务
     * @param reqMap
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int completeTask(User currentUser, Map<String, Object> reqMap) {
        reqMap.put("t_id", UuidUtil.get32UUID());
        reqMap.put("user_id", currentUser.getId());
        //抽奖奖品加50积分
        if (reqMap.get("prize") != null && "scores".equals(reqMap.get("prize").toString())) {
            // 把数据插入到积分记录表
            this.saveIntegrationRecordForTask("0", "中奖积分兑换", 50, currentUser.getId());
            // 获取当前用户的积分
            int integration = currentUser.getIntegration();
            // 用户加积分
            return userDao.updateIntegration(currentUser.getId(), integration + 50);
        }
        //获取任务信息
        TaskConfig taskInfo = personalCenterMapper.getTaskInfo(reqMap);
        String type = taskInfo.getType();
        //加到客户任务表
        int result = personalCenterMapper.completeTask(reqMap);
        int score = taskInfo.getScore();
        String name;
        int id = Integer.valueOf(reqMap.get("id").toString()) ;
        if (id == 1) {
            name = "每日分享";
        } else if (id == 2) {
            name = "每日发布";
        } else if (id == 3) {
            name = "每日收藏";
        } else if (id == 4) {
            name = "每日浏览";
        }else if (id == 5) {
            name = "申请体验机修师盒子";
        } else if (id == 6) {
            name = "日常签到";
            int signInCount = Integer.valueOf(reqMap.get("signIn_count").toString());
            score = this.getIntegration(signInCount);
            if (score == 0) {
                return 0;
            }
        } else if (id == 7) {
            name = "邀请好友";
        } else {
            name = "每日任务";
        }
        reqMap.put("name", name);
        // 完成此任务需要的次数
        int needTimes = taskInfo.getTimes();
        // 今天完成此任务的次数
        int todayTimes = personalCenterMapper.getTodayTimes(currentUser.getId(), String.valueOf(id));
        // 一次性任务已经完成的次数
        int oneTaskTimes = personalCenterMapper.getOneTaskTimes(currentUser.getId(),id);
        if (type.equals("1") && todayTimes <= needTimes||type.equals("3") && oneTaskTimes==needTimes||type.equals("2") && todayTimes == needTimes) {
            reqMap.put("score_id", UuidUtil.get32UUID());
            // 把数据插入到积分记录表
            this.saveIntegrationRecordForTask(String.valueOf(id), name, score, currentUser.getId());
            // 获取当前用户的积分
            int integration = currentUser.getIntegration();
            // 用户加积分
            userDao.updateIntegration(currentUser.getId(), integration + score);
        }

        return result;
    }

    private int getIntegration(int signInCount) {
        int count = signInCount % 7;
        if (count == 1) {
            return 1;
        } else if (count == 2) {
            return 2;
        } else if (count == 3) {
            return 4;
        } else if (count == 4) {
            return 8;
        } else if (count == 5) {
            return 16;
        } else if (count == 6) {
            return 32;
        }
        return 0;
    }

    @Override
    public Map<String, Object> getCurrentCreditAndIntegration(User currentUser) {
        Map<String,Object> companyApplyMap = new HashMap<>();
        String id = currentUser.getId();
        String s_id = currentUser.getS_id();
        String r_id = currentUser.getR_id();

        int flag = 0;
        Map<String,Object> resultMap = personalCenterMapper.getCurrentCreditAndIntegration(id);

        resultMap.put("s_id",s_id);

        // 可用额度
        Double userAvailableLimit = 0.0;

        resultMap.put("userAvailableLimit",userAvailableLimit);

        // 只查询车主
        if (r_id.equals(Constants.ROLE_CZ)) {

            // 获取用户还款总额度
            Double orderRepaymentSum = 0.0;
            // 获取用户使用总额度
            Double orderUseSum = 0.0;

            if (orderDao.getOrderRepaymentSum(resultMap) != null) {

                orderRepaymentSum = Math.ceil(orderDao.getOrderRepaymentSum(resultMap));
            }

            if (orderDao.getOrderUseSum(resultMap) != null) {

                orderUseSum = Math.ceil(orderDao.getOrderUseSum(resultMap));
            }

            // 当前欠款
            Double nowDebt = orderUseSum - orderRepaymentSum;
            Double credit_limit =0d;
            if (resultMap.get("credit_limit")!=null){
                credit_limit = Math.ceil(Double.parseDouble(resultMap.get("credit_limit").toString()));
            }
            // 欠款小于信用额度
            if (nowDebt < credit_limit) {

                // 当前可用总额度
                userAvailableLimit = credit_limit - nowDebt;

                resultMap.put("userAvailableLimit",userAvailableLimit);
            }
        }

        Map totalMap = userDao.getMyCollectionAndPublishTotal(id);
        if("7".equals(r_id)){
            //获取此用户发布的新机数量
            long thisUserPublishNewCount = userDao.getThisUserPublishNewCount(id,2);
            //获取同一个服务商下的所有发布的新机数量
            long serverNewCount = userDao.getServerNewCount(s_id,2);
            long count = (long)totalMap.get("publishTotal") - thisUserPublishNewCount + serverNewCount;
            totalMap.put("publishTotal",count);
        }
        if (totalMap != null) {
            resultMap.put("collectionTotal", totalMap.get("collectionTotal"));
            resultMap.put("publishTotal", totalMap.get("publishTotal"));
        }
        //企业认证附件表里是否存在此用户
        int isExist = personalCenterMapper.companyApplyExist(id);
        //申请标识
        if(isExist>0){
            flag = personalCenterMapper.getProvementFlag(id);
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
        if(flag==0){
            //未申请
            companyApplyMap.put("flag",0);
        } else if(flag==1){
            //审核中
            companyApplyMap.put("flag",1);
        }else if(flag==2){
            //未通过
            Date finishDate = personalCenterMapper.getFinishDate(id);
            //结束日期
            String finishTime = format.format(finishDate);
            companyApplyMap.put("flag",2);
            companyApplyMap.put("finishTime",finishTime);
        }else if(flag==3){
            //审核通过
            Map<String,Object> companyApplyPassInfo = personalCenterMapper.companyApplyPassInfo(id);
            //已经成为认证企业的天数
            String passDays = companyApplyPassInfo.get("passDays").toString();
            //通过日期
            String passTime = companyApplyPassInfo.get("passTime").toString();
            //企业名称
            String companyName = companyApplyPassInfo.get("companyName").toString();
            companyApplyMap.put("flag",3);
            companyApplyMap.put("passTime",passTime);
            companyApplyMap.put("passDays",passDays);
            companyApplyMap.put("companyName",companyName);
        }
        companyApplyMap.put("userName",currentUser.getUser_name());
        resultMap.put("companyApplyMap",companyApplyMap);
        resultMap.put("couponCount",0);
        //查询优惠券数量
        try {
            resultMap.put("couponCount",personalCenterMapper.selectCouponCount(id));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return resultMap;
    }

    /**
     * 中奖纪录表
     * @param reqMap
     * @param currentUser
     * @return
     */
    @Override
    public Map<String, Object> getCustomerPrizeList(Map<String, Object> reqMap,User currentUser) {
        reqMap.put("user_id",currentUser.getId());
        Map<String,Object> resultMap = new HashMap<>();
        int count = personalCenterMapper.customerPrizeCount(reqMap);
        Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(), reqMap.get("currentPage").toString());
        reqMap.put("currentPage", pageMap.get("offset"));
        reqMap.put("pageSize", pageMap.get("limit"));
        int pageSize = (int) pageMap.get("limit");
        List<Map<String, Object>> list = personalCenterMapper.getCustomerPrizeList(reqMap);
        //页数
        for(Map<String,Object> map:list){
            if(map.get("name")!=null){
                map.put("status","1");
            }else{
                map.put("status","0");
            }
        }
        int pages = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
        resultMap.put("count",count);
        resultMap.put("pages", pages);
        resultMap.put("list", list);
        return resultMap;
    }

    @Override
    public int fillGetPrizeInfo(Map<String, Object> reqMap, User currentUser) {
        reqMap.put("user_id",currentUser.getId());
        int result = personalCenterMapper.fillGetPrizeInfo(reqMap);
        return result;
    }

    /**
     * 我的积分明细列表
     * @param reqMap
     * @return
     */
    @Override
    public List<IntegrationRecord> myIntegrationRecordList(User currentUser, Map<String, Object> reqMap) {
        this.appPage(reqMap);
        reqMap.put("userId", currentUser.getId());
        return personalCenterMapper.listIntegrationRecordByUserId(reqMap);
    }

    /**
     * 我的兑换记录列表
     * @param reqMap
     * @return
     */
    @Override
    public List<IntegrationExchangeRecord> myIntegrationExchangeRecord(User currentUser, Map<String, Object> reqMap) {
        this.appPage(reqMap);
        reqMap.put("userId", currentUser.getId());
        return personalCenterMapper.listIntegrationExchangeRecordByUserId(reqMap);
    }

    /**
     * 获取商品列表
     * @param currentUser
     * @param reqMap
     * @return
     */
    @Override
    public List<IntegrationGoods> listIntegrationGoods(User currentUser, Map<String, Object> reqMap) {
        this.appPage(reqMap);
        return personalCenterMapper.listIntegrationGoods(reqMap);
    }

    /**
     * 兑换奖品
     * @param currentUser
     * @param integrationExchangeRecord
     * @return
     * @throws MyException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean exchangeGoods(User currentUser, IntegrationExchangeRecord integrationExchangeRecord) throws MyException {
        // 查找商品
        IntegrationGoods integrationGoods = personalCenterMapper.getIntegrationGoodsById(integrationExchangeRecord.getIntegrationGoodsId());
        if (integrationGoods == null) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "不存在这个商品");
        }
        // 查看用户当前积分是否足够
        int goodsScore = integrationGoods.getScore();
        if (currentUser.getIntegration() == 0 || currentUser.getIntegration() < goodsScore) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "积分不足");
        }
        // 存进兑换记录表
        integrationExchangeRecord.setId(UuidUtil.get32UUID());
        integrationExchangeRecord.setUserId(currentUser.getId());
        integrationExchangeRecord.setIntegrationGoodsName(integrationGoods.getName());
        integrationExchangeRecord.setScore(-goodsScore);
        personalCenterMapper.saveIntegrationExchangeRecord(integrationExchangeRecord);
        // 生成积分明细记录
        this.saveIntegrationRecordForGoods(integrationGoods.getId(), -goodsScore, currentUser.getId());
        // 更新用户总积分
        int remainIntegration = currentUser.getIntegration() - goodsScore;
        userDao.updateIntegration(currentUser.getId(), remainIntegration);
        return true;
    }

    /**
     * 购买商品积分明细记录
     * @param integrationGoodsId
     * @param userId
     * @return
     */
    private int saveIntegrationRecordForGoods(String integrationGoodsId, int score, String userId) {
        return this.saveIntegrationRecord("", integrationGoodsId, "积分兑换", score, userId);
    }

    /**
     * 做任务积分明细记录
     * @param taskId
     * @param name
     * @param userId
     * @return
     */
    private int saveIntegrationRecordForTask(String taskId, String name, int score, String userId) {
        return this.saveIntegrationRecord(taskId, "", name, score, userId);
    }

    /**
     * 保存任务明细记录
     * @param taskId
     * @param integrationGoodsId
     * @param name
     * @param userId
     * @return
     */
    private int saveIntegrationRecord(String taskId, String integrationGoodsId, String name, int score, String userId) {
        IntegrationRecord integrationRecord = new IntegrationRecord();
        integrationRecord.setId(UuidUtil.get32UUID());
        integrationRecord.setTaskId(taskId);
        integrationRecord.setIntegrationGoodsId(integrationGoodsId);
        integrationRecord.setScore(score);
        integrationRecord.setName(name);
        integrationRecord.setUserId(userId);
        return personalCenterMapper.saveIntegrationRecord(integrationRecord);
    }

    /**
     * 访问出售，求购，出租，求租时插入记录
     * @param reqMap
     * @param currentUser
     * @param context
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int pushVisitMessage(Map<String,Object> reqMap,User currentUser,String context){
        int result = 0;
        String userId = currentUser.getId();
        String receiver = reqMap.get("receive_user").toString();
        if(!userId.equals(receiver)){
            reqMap.put("id",UuidUtil.get32UUID());
            reqMap.put("user",userId);
            reqMap.put("s_id",currentUser.getS_id());
            reqMap.put("client","YD");
            result = messageRecordDao.addMessageRecord(reqMap);
        }
        return result;
    }

    /**
     * 获取访问人列表记录
     * @param currentUser
     * @param reqMap
     * @return
     */
    @Override
    public Map<String,Object> getVisitList(User currentUser, Map<String, Object> reqMap) {
        reqMap.put("user_id",currentUser.getId());
        Map<String,Object> resultMap = new HashMap<>();
        int count = personalCenterMapper.getVisitListCount(reqMap);
        Map<String, Object> pageMap = Page.appPage(reqMap.get("pageSize").toString(), reqMap.get("currentPage").toString());
        reqMap.put("currentPage", pageMap.get("offset"));
        reqMap.put("pageSize", pageMap.get("limit"));
        int pageSize = (int) pageMap.get("limit");
        List<Map<String,Object>> visitList = personalCenterMapper.getVisitList(reqMap);
        int pages = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
        resultMap.put("count",count);
        resultMap.put("pages", pages);
        resultMap.put("visitList",visitList);
//
//        Set<String> uniqueContexts = new HashSet<>();
//        // 用于存储不重复的context值
//        List<String> uniqueContextList = new ArrayList<>();
//
//        for (Map<String, Object> visit : visitList) {
//            String context = (String) visit.get("context");
//
//            // 检查context是否已经存在于uniqueContexts中
//            if (!uniqueContexts.contains(context)) {
//                uniqueContexts.add(context); // 将context添加到uniqueContexts中
//                uniqueContextList.add(context); // 将不重复的context添加到uniqueContextList中
//            }
//        }
//        //设置定时器进行10点推送
//        Timer timer = new Timer();
//
//        // 获取当前时间
//        Calendar now = Calendar.getInstance();
//
//        // 计算距离明天十点的时间间隔（毫秒）
//       // long delay = calculateDelay(now);
//
//        long delay = 10 * 1000; // 1分钟
//        // 创建定时任务
//        TimerTask task = new TimerTask() {
//            public void run() {
//                // 在这里编写发送消息的逻辑
//                logger.info("十点发送消息");
//                // 浏览
//                int accessCount=personalCenterMapper.getAccessCount(reqMap);
//                //收藏
//                int favoriteCount=personalCenterMapper.getFavoriteCount(reqMap);
//                //转发
//                int forwardCount=personalCenterMapper.getForwardCount(reqMap);
//                Map<String, Object> messageMap = new HashMap<>();
//                if (accessCount != 0 || favoriteCount != 0 || forwardCount != 0){
//                    for (String context : uniqueContextList) {
//                        //APP推送消息
//                        messageMap.put("push_user_id",currentUser.getId());
//                        messageMap.put("title", "浏览信息");
//                        messageMap.put("push_content", "您发布的"+context+"信息昨日被浏览"+accessCount+"次，被收藏"+favoriteCount+"次，"+"被转发"+forwardCount+"次，点此查看详情>>>");
//                        messageMap.put("create_user", currentUser.getId());
//                        jiGuangPushUtil.publishMessagePush(messageMap, PushConstants.TITLE_NEWOROLD_MACHINE_BROSE_WARNING, "", UuidUtil.get32UUID());
//                        //保存到数据库中
//                        reqMap.put("id",UuidUtil.get32UUID());
//                        reqMap.put("user",currentUser.getId());
//                        reqMap.put("s_id",currentUser.getS_id());
//                        //send_type=400,当有人浏览/转发的type
//                        reqMap.put("send_type",400);
//                        reqMap.put("receive_user",currentUser.getId());
//                        reqMap.put("client","YD");
//                        reqMap.put("context",context);
//                        reqMap.put("extra_params", "{\"push_tuisong\":\""+ reqMap.get("id").toString() +"\"}");
//                        messageRecordDao.addMessageRecord(reqMap);
//                    }
//                }
//            }
//        };
//        // 每天十点执行一次任务
//        //timer.schedule(task, delay, 24 * 60 * 60 * 1000);
//        // 每隔1分钟执行一次任务
//        timer.schedule(task, delay, delay);
        return resultMap;
    }

//    /**
//     * 设置每日10点推送
//     * @param now
//     * @return
//     */
//    private static long calculateDelay(Calendar now) {
//        Calendar tomorrowTenAM = Calendar.getInstance();
//        tomorrowTenAM.set(Calendar.HOUR_OF_DAY, 10);
//        tomorrowTenAM.set(Calendar.MINUTE, 0);
//        tomorrowTenAM.set(Calendar.SECOND, 0);
//
//        // 如果当前时间已经超过了明天的十点，则定时任务应该在明天的十点执行
//        if (now.after(tomorrowTenAM)) {
//            tomorrowTenAM.add(Calendar.DAY_OF_MONTH, 1);
//        }
//
//        return tomorrowTenAM.getTimeInMillis() - now.getTimeInMillis();
//    }
    /**
     * 获取访问数量
     * @param currentUser
     * @param reqMap
     * @return
     */
    @Override
    public Map<String, Object> getVisitCount(User currentUser, Map<String, Object> reqMap) {
        Map<String,Object> resultMap = new HashMap<>();
        reqMap.put("receive_user",currentUser.getId());
        int todayVisitCount = personalCenterMapper.getTodayVisitCount(reqMap);
        int totalVisitCount = personalCenterMapper.getTotalVisitCount(reqMap);
        resultMap.put("todayVisitCount",todayVisitCount);
        resultMap.put("totalVisitCount",totalVisitCount);
        return resultMap;
    }

    /**
     * 转发后推送
     * @param currentUser
     * @param reqMap
     * @return
     */
    @Override
   // @Async
    public int insertRedirect(User currentUser, Map<String, Object> reqMap) {
        int result = 0;
        String context = "";
        String userId = currentUser.getId();
        if(reqMap.get("create_user")!=null&&reqMap.get("subject")!=null||reqMap.get("create_user")!=null&&reqMap.get("shop_name")!=null){
            if(reqMap.get("subject")!=null){
                 context = reqMap.get("subject").toString();
            }
            if(reqMap.get("shop_name")!=null){
                 context = reqMap.get("shop_name").toString();
            }
            String receiver = reqMap.get("create_user").toString();
//            String id = UuidUtil.get32UUID();
//            reqMap.put("id", id);
//            //推送给相应用户
//            // 创建一个 resultMap 对象
//
//            Map<String, String> extraParamsMap = new HashMap<>();
//            extraParamsMap.put(PushConstants.KEY_PUSH_QIUGOU, reqMap.get("id").toString());
//
//            List<Map<String, String>> guanliyuanList = appDao.getGuanliyuanMapList(reqMap);
//            guanliyuanList.forEach(guanliyuanItem -> {
//                String guanliyuanUserId = guanliyuanItem.get("id");
//
//                Map<String, Object> messageMap = new HashMap<>();
//                messageMap.put("push_user_id", guanliyuanUserId);
//                messageMap.put("title", "转发信息");
//                messageMap.put("push_content", "("+ reqMap.get("u_name").toString() +")("+ reqMap.get("mobile_phone").toString() +")已转发您发布的出租/出售信息，请查看>>>");
//                messageMap.put("create_user", currentUser.getId());
//
//                // 推送消息并且保存推送信息
//                PushResult pushResultresult = jiGuangPushUtil.publishMessagePush(messageMap, PushConstants.KEY_PUSH_QIUGOU, "", extraParamsMap, UuidUtil.get32UUID());
//
//            });

            if(!userId.equals(receiver)){
                reqMap.put("id",UuidUtil.get32UUID());
                reqMap.put("user",userId);
                reqMap.put("s_id",currentUser.getS_id());
                reqMap.put("send_type",12);
                reqMap.put("receive_user",receiver);
                reqMap.put("client","YD");
                reqMap.put("context",context);
                reqMap.put("extra_params", "{\"push_zhuanfa\":\""+ reqMap.get("id").toString() +"\"}");
                result = messageRecordDao.addMessageRecord(reqMap);
            }
        }
        return result;
    }

    /**
     * 获取系统通知列表 分页
     * @param currentUser
     * @param reqMap
     * @return
     */
    @Override
    public Map<String, Object> getSystemInform(User currentUser, Map<String, Object> reqMap) {
        reqMap.put("user_id", currentUser.getId());
        Map<String, Object> resultMap = new HashMap<>();
        int count = personalCenterMapper.getSystemInformCount(reqMap);
        appPage(reqMap);
        List<Map<String, Object>> list = personalCenterMapper.getSystemInformList(reqMap);
        for (Map<String, Object> map : list) {
            int sendType = Integer.parseInt(map.get("send_type").toString());
            if (sendType == 0 || sendType == 1 || sendType == 2 || sendType == 3 || sendType == 5 || sendType == 6) {
                map.put("subject", "工单消息");
            } else if (sendType == 8) {
                map.put("subject", "报警信息");
            } else if (sendType == 10) {
                map.put("subject", "有人访问了您");
            } else if (sendType == 11) {
                map.put("subject", "有人收藏了您");
            } else if (sendType == 12) {
                map.put("subject", "有人转发了您");
            } else if (sendType == 13) {
                map.put("subject", "申请解锁");
            }  else if (sendType == 14) {
                map.put("subject", PushConstants.TITLE_CAR_MAINTENANCE_WARNING);
            }  else if (sendType == 15) {
                map.put("subject", PushConstants.TITLE_CAR_OIL_LEVEL_WARNING);
            }  else if (sendType == 16) {
                map.put("subject", PushConstants.TITLE_CAR_FAULT_WARNING);
            } else if (sendType == 17) {
                map.put("subject", PushConstants.TITLE_CAR_TEMPERATURE_WARNING);
            } else if (sendType == 18) {
                map.put("subject", PushConstants.TITLE_CAR_TEMPERATURE_HIGH_WARNING);
            } else if (sendType == 21) {
                map.put("subject", "求购信息");
            } else if (sendType == 30) {
                map.put("subject", PushConstants.TITLE_CAR_OIL_TEMPERATURE_WARNING);
            } else if (sendType == 31) {
                map.put("subject", PushConstants.TITLE_CAR_OIL_PRESSURE_WARNING);
            } else if (sendType == 32) {
                map.put("subject", PushConstants.TITLE_CAR_HIGHHDLOIL_TEMPERATURE_WARNING);
            } else if (sendType == 33) {
                map.put("subject", PushConstants.TITLE_CAR_LOWHDLOIL_TEMPERATURE_WARNING);
            } else if (sendType == 34) {
                map.put("subject", PushConstants.TITLE_CAR_IDLEHIGH_TIME_WARNING);
            } else if (sendType == 35) {
                map.put("subject", PushConstants.TITLE_CAR_MAINTENANCE_WARNING);
            } else if (sendType == 36) {
                map.put("subject", PushConstants.TITLE_MODELCOMPARISON_WARNING);
            } else if (sendType == 37) {
                map.put("subject", PushConstants.TITLE_NEWOROLD_MACHINE_BROSE_WARNING);
            } else if (sendType == 100) {
                map.put("subject", PushConstants.TITLE_CREDIT_LIMIT_WARNING);
            } else if (sendType == 101) {
                map.put("subject", PushConstants.TITLE_CAR_FREE_WARNING);
            } else if (sendType == 102) {
                map.put("subject", PushConstants.TITLE_LIGHT_SENCE_WARNING);
            } else if (sendType == 105) {
                map.put("subject", PushConstants.LOCKCAR_WARNING);
            } else if (sendType == 106) {
                map.put("subject", PushConstants.UNLOCKCAR_WARNING);
            } else if (sendType == 107) {
                map.put("subject", PushConstants.TITLE_REMIND_REPAYMENT_WARNING);
            } else if (sendType == 110) {
                map.put("subject", PushConstants.TITLE_LIGHT_SENCE_WARNING);
            } else if (sendType == 111) {
                map.put("subject", PushConstants.TITLE_LIGHT_SENCE_WARNING);
            } else if (sendType == 113) {
                map.put("subject", PushConstants.TITLE_ENCLOSURE_BLACK);
            } else if (sendType == 7) {
                map.put("subject", PushConstants.TITLE_ENCLOSURE);
            } else if (sendType == 200) {  // 还款期前还款成功的消息类型为 200 (从200起始)
                map.put("subject", PushConstants.TITLE_REMIND_ACCOUNTING_PERIOD);
            } else if (sendType == 201) {  // 补缴欠款成功提醒的消息类型为 201 (从200起始)
                map.put("subject", PushConstants.TITLE_REMIND_SUPPLEMENTARY_PAYMENT);
            } else if (sendType == 202) {  // 解锁申请已通过的消息类型为 202 (从200起始)
                map.put("subject", PushConstants.TITLE_REMIND_APPLICATIONPASSED);
            } else if (sendType == 203) {  // 解锁申请已拒绝的消息类型为 203 (从200起始)
                map.put("subject", PushConstants.TITLE_REMIND_APPLICATIONREJECT);
            } else {
                map.put("subject", "");
            }
        }
        int pageSize = (int) reqMap.get("pageSize");
        int pages = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
        resultMap.put("pages", pages);
        resultMap.put("count", count);
        resultMap.put("list", list);
        return resultMap;
    }

    /**
     * 设置系统通知状态
     * @param currentUser
     * @param reqMap
     * @return
     */
    @Override
    public int setSystemInformReaded(User currentUser, Map<String, Object> reqMap) {
        reqMap.put("user_id",currentUser.getId());
        int result = personalCenterMapper.setSystemInformReaded(reqMap);
        return result;
    }

    /**
     * 设置系统通知状态
     * @param currentUser
     * @param reqMap
     * @return
     */
    @Override
    public int getUnreadCount(User currentUser, Map<String, Object> reqMap) {
        int result = personalCenterMapper.getUnreadCount(reqMap);
        return result;
    }

    /**
     * 获取七天访问量
     * @param currentUser
     * @param reqMap
     * @return
     */
    @Override
    public Map<String, Object> getWeekVistorCount(User currentUser, Map<String, Object> reqMap) {
        reqMap.put("user_id",currentUser.getId());
        Map<String,Object> resultMap = new HashMap<>();
        List<Map<String,Object>> list = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for(int i=0;i<7;i++){
            Date date = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.DAY_OF_MONTH,-i);
            Date calendarTime = calendar.getTime();
            reqMap.put("calendarTime",calendarTime);
            Map<String,Object> map = personalCenterMapper.getDayVistorCount(reqMap);
            String dateString = simpleDateFormat.format(calendarTime);
            map.put("date",dateString);
            if(i==0){
                map.put("date","今日");
            }
            if(i==6){
                map.put("date","7天前");
            }
            list.add(map);
        }
        Collections.reverse(list);
        resultMap.put("list",list);
        return resultMap;
    }

    /**
     * 申请企业认证
     * @param reqMap
     * @param currentUser
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int companyApply(Map<String, Object> reqMap, User currentUser) {
        reqMap.put("user_id",currentUser.getId());
        reqMap.put("id",UuidUtil.get32UUID());
        if(reqMap.get("image")!=null){
            String image = reqMap.get("image").toString();
            String[]  pictureList = image.split(",");
            for(int index=0;index<pictureList.length;index++){
                reqMap.put("a_id",UuidUtil.get32UUID());
                reqMap.put("picture_path",pictureList[index]);
                int imgResult = personalCenterMapper.companyApplyImg(reqMap);
            }
        }
        int result = personalCenterMapper.companyApply(reqMap);
        return result;
    }

    /**
     * 修改企业认证
     * @param reqMap
     * @param currentUser
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateCompanyApply(Map<String, Object> reqMap, User currentUser) {
        reqMap.put("user_id",currentUser.getId());
        String id = personalCenterMapper.getCompanyApplyId(reqMap);
        reqMap.put("id",id);
        int result = personalCenterMapper.updateCompanyApply(reqMap);
        if(reqMap.get("image")!=null){
            //先删除原先的图片
            int deleteResult = personalCenterMapper.deleteCompanyApplyImg(reqMap);
            String image = reqMap.get("image").toString();
            String[]  pictureList = image.split(",");
            for(int index=0;index<pictureList.length;index++){
                reqMap.put("a_id",UuidUtil.get32UUID());
                reqMap.put("picture_path",pictureList[index]);
                int imgResult = personalCenterMapper.companyApplyImg(reqMap);
            }

        }
        return result;
    }

    /**
     * 企业认证详情
     * @param reqMap
     * @param currentUser
     * @return
     */
    @Override
    public Map<String, Object> companyApplyInfo(Map<String, Object> reqMap, User currentUser) {
        reqMap.put("user_id",currentUser.getId());
        String image = "";
        Map<String,Object> resultMap = personalCenterMapper.companyApplyInfo(reqMap);
        List<String> imageList = personalCenterMapper.getCompanyApplyImageList(reqMap);
        if(imageList!=null){
            for(int index=0;index<imageList.size()-1;index++){
                image += imageList.get(index)+",";
            }
            image += imageList.get(imageList.size()-1);
            resultMap.put("image",image);
        }
        return resultMap;
    }

    @Override
    public String addIsCompanyPublish(Map<String, Object> reqMap) {
        List<String> list = personalCenterMapper.getCompany();
        for(String str:list){
            reqMap.put("create_user",str);
            personalCenterMapper.updateRecruitPublish(reqMap);
            personalCenterMapper.updateJoberPublish(reqMap);
            personalCenterMapper.updateShopPublish(reqMap);
            personalCenterMapper.UpdateZsPublish(reqMap);
        }
        return "ok";
    }

    @Override
    public int carDataCalibration(Map<String, Object> reqMap) {

        String things_id = reqMap.get("things_id").toString();
        String DIO = reqMap.get("DIO").toString();
        String DIO_tilte = reqMap.get("DIO_tilte").toString();

        List<Map<String,Object>> dataMap = (List<Map<String,Object>>)reqMap.get("dataMap");

        dataMap.forEach(item ->{

            String data_time = item.get("data_time").toString();
            String date_value = item.get("date_value").toString();

            reqMap.put("things_id",things_id);
            reqMap.put("DIO",DIO);
            reqMap.put("DIO_tilte",DIO_tilte);
            reqMap.put("data_time",data_time);
            reqMap.put("date_value",date_value);

            personalCenterMapper.carDataCalibration(reqMap);
        });

        return 1;
    }

    // 获取数据校准
    @Override
    public List<Map<String, Object>> getCarDataCalibration(Map<String, Object> reqMap) {

        return personalCenterMapper.getCarDataCalibration(reqMap);
    }

    @Override
    public int getUnreadCountOfType(Map<String, Object> reqMap) {
        String sendTypeInList = "";
        String type = reqMap.get("type").toString();
        // 发送类型
        // 7：电子围栏报警 8：实数数据超限报警 9：故障码报警
        // 10：访问 11：收藏 12：转发
        // 13：申请解锁' 14-车辆工作小时达到保养的工时 15-车辆油位低于x%的时候 16-车辆报出故障代码的时候
        // 7,8,9,13,14,15,16,17,18 - 1:设备提醒
        // 0,1,2,3,5,6             - 2:工单提醒
        // 4,10,11                 - 3:商机推送
        // 12,20                   - 4:消息通知
        // 1:设备提醒; 2:工单提醒;3:商机推送;4:消息通知
        if(type.equals("1")) {
           //sendTypeInList = "(7,8,9,13,14,15,16,17,18,32)";//32 液压油温度报警
            sendTypeInList = "(7,8,9,13,14,15,16,17,18,20,30,31,32,33,34,35,102,105,106,113,300)";
        } else if(type.equals("2")) {
            //sendTypeInList = "(0,1,2,3,5,6)";
           // sendTypeInList = "(0,1,2,3,5,6,14,20,31,32,33,34,35,105,106,110,111,112,300)";
           // sendTypeInList = "(0,1,2,3,5,6,14,20,110,111,112,300)";
            sendTypeInList = "(0,1,2,3,5,6,14,20,112,300)";
        } else if(type.equals("5")) {
           // sendTypeInList = "(4,10,11)";
            sendTypeInList = "(4,10,11,12,21,36,37,110,111,400)";
        } else if(type.equals("4")) {
            sendTypeInList = "(12,20)";
        }
        reqMap.put("sendTypeInList", sendTypeInList);
        int count = personalCenterMapper.getUnreadCountOfType(reqMap);
        return count;
    }

    @Override
    public PageInfo getMessageList(Map<String, Object> reqMap) {
        String sendTypeInList = "";
        String type = reqMap.get("type").toString();
        // 发送类型
        // 7：电子围栏报警 8：实数数据超限报警 9：故障码报警
        // 10：访问 11：收藏 12：转发
        // 13：申请解锁' 14-车辆工作小时达到保养的工时 15-车辆油位低于x%的时候 16-车辆报出故障代码的时候
        // 7,8,9,13,14,15,16,17,18 - 1:设备提醒
        // 0,1,2,3,5,6             - 2:工单提醒
        // 4,10,11                 - 3:商机推送
        // 12,20                   - 4:消息通知
        // 1:设备提醒; 2:工单提醒;3:商机推送;4:消息通知
        if(type.equals("1")) {
           // sendTypeInList = "(7,8,9,13,14,15,16,17,18)";
            sendTypeInList = "(7,8,9,13,14,15,16,17,18,20,30,31,32,33,34,35,102,105,106,113,300)";
        } else if(type.equals("2")) {
           // sendTypeInList = "(0,1,2,3,5,6)";
           // sendTypeInList = "(0,1,2,3,5,6,14,20,31,32,33,34,35,105,106,110,111,112,300)";
            sendTypeInList = "(0,1,2,3,5,6,14,20,112,300)";
        } else if(type.equals("5")) {
           //sendTypeInList = "(4,10,11)";
            sendTypeInList = "(4,10,11,12,21,36,37,110,111,400)";
        } else if(type.equals("4")) {
            sendTypeInList = "(12,20)";
        }
        reqMap.put("sendTypeInList", sendTypeInList);

        Integer pageSize = Integer.valueOf(reqMap.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(reqMap.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> mapList = personalCenterMapper.getMessageList(reqMap);
        PageInfo<Map<String, Object>> mapPageInfo = new PageInfo<>(mapList);
        return mapPageInfo;
    }

    // 后市场查看各类消息的列表
    // 发送类型
    // 7：电子围栏报警(113: 黑区电子围栏报警) 8：实数数据超限报警 9：故障码报警(9 暂时没用到, send_type 使用 16)
    // 10：访问 11：收藏 12：转发
    // 13：申请解锁' 14-车辆工作小时达到保养的工时 15、20、10-车辆油位低于x%的时候 16-车辆报出故障代码的时候 17-发动机冷却剂温度
    // 7,8,9,13,14,15,16,17,18 - 1:设备提醒
    // 0,1,2,3,5,6             - 2:工单提醒
    // 4,10,11,12              - 3:商机推送
    // 20                      - 4:消息通知
    // 1:设备提醒; 2:工单提醒;3:商机推送;4:消息通知
    @Override
    public PageInfo getMessageRecordList(Map<String, Object> reqMap) {
        String sendTypeInList = "";
        String type = reqMap.get("type").toString();
        if(type.equals("1")) {  //34怠速报警    35保养提醒   105锁车  106解锁
          //  sendTypeInList = "(7,8,9,13,15,16,17,18,20,30,31,32,33,34,35,102,105,106,113,300)";//新加32,33 液压油温度过高或过低。31 机油压力过高。30机油温度过高
            sendTypeInList = "(7,8,9,13,15,16,17,18,20,30,31,32,33,34,35,102,105,106,113,300)";
            String sendType = reqMap.get("send_type").toString();
            if(!sendType.equals("-1")) {
                reqMap.put("sendTypeGroup", "send_type = " + sendType); // send_type 只有一种选项
            }
        } else if(type.equals("2")) {
            //sendTypeInList = "(0,1,2,3,5,6,4,10,11,12,14,20,31,32,33,34,35,105,106,110,111,112,300)";  // 14 为保养消息，归为一般消息
          //  sendTypeInList = "(0,1,2,3,5,6,14,20,31,32,33,34,35,105,106,110,111,112,300)";  // 14 为保养消息，归为一般消息
            //sendTypeInList = "(0,1,2,3,5,6,14,20,110,111,112,300)";  // 14 为保养消息，归为一般消息
            sendTypeInList = "(0,1,2,3,5,6,14,20,112,300)";  // 14 为保养消息，归为一般消息
            String sendType = reqMap.get("send_type").toString();
            if(!sendType.equals("-1")) {
                if(sendType.equals("0")) {
                    reqMap.put("sendTypeGroup", "(send_type = 0 or send_type = 1 or send_type = 2 or send_type = 3 or send_type = 5 or send_type = 6)");  // send_type 有多种选项
                } else if(sendType.equals("4")) {
                    reqMap.put("sendTypeGroup", "(send_type = 4 or send_type = 10 or send_type = 11 or send_type = 12 )");  // send_type 有多种选项
                } else if(sendType.equals("12")) {
                    reqMap.put("sendTypeGroup", "(send_type = 14 or send_type = 20 or send_type = 110 or send_type = 111 or send_type = 112)");  // send_type 有多种选项
                }
            }
        } else if (type.equals("5")) { //商机推送，type=3已被占用
            sendTypeInList = "(4,10,11,12,21,36,37,110,111,400)";  // 36 机型对比推送， 37 新机、二手机浏览推送  21发布求购  ,10浏览信息，11收藏信息,400浏览推送每天十点
            String sendType = reqMap.get("send_type").toString();
            if(!sendType.equals("-1")) {
                reqMap.put("sendTypeGroup", "send_type = " + sendType); // send_type 只有一种选项
            }
        } else if (type.equals("10")) { //查全部信息
            sendTypeInList = "(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,20,21,30,31,32,33,34,35,36,37,102,105,106,110,111,112,113,300,400)";
        }
//        else if (type.equals("6")) { //系统消息
//            sendTypeInList = "(14,20,110,111,112,113,300)";
//        }
        else {
            sendTypeInList = "(-1)";
        }
        reqMap.put("sendTypeInList", sendTypeInList);

        Integer pageSize = Integer.valueOf(reqMap.get("pageSize").toString());
        Integer currentPage = Integer.valueOf(reqMap.get("currentPage").toString());
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String, Object>> list = personalCenterMapper.getMessageRecordList(reqMap);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public int updateMessageRecordListForIds(Map<String, Object> reqMap) {
        int result = personalCenterMapper.updateMessageRecordListForIds(reqMap);
        return result;
    }

    @Override
    public int updateMessageRecordListForSid(Map<String, Object> reqMap) {
        String sendTypeInList = "";
        String type = reqMap.get("type").toString();
        if(type.equals("1")) {
            sendTypeInList = "(7,8,9,13,14,15,16,17,18)";
        } else if(type.equals("2")) {
            sendTypeInList = "(0,1,2,3,5,6,4,10,11,12,20,112)";
        } else {
            sendTypeInList = "(-1)";
        }
        reqMap.put("sendTypeInList", sendTypeInList);

        int result = personalCenterMapper.updateMessageRecordListForSid(reqMap);
        return result;
    }

    @Override
    public int updateMessageHandleStatusById(Map<String, Object> paraMap) {
        int result = personalCenterMapper.updateMessageHandleStatusById(paraMap);
        return result;
    }

    @Override
    public int selectAllRenewalNoHandleMessageCount(Map<String, Object> paraMap) {
        int count = personalCenterMapper.selectAllRenewalNoHandleMessageCount(paraMap);
        return count;
    }
}